import os
from urllib import request, parse
import json

try:
    from .cvio import cvio
    from .testService import encodeImg
except:
    from cvio import cvio
    from testService import encodeImg

def scls_classify(url, src, score=0.5, topk=1, batch_size=1):
    if os.path.isdir(src):
        imgs = cvio.load_image_list(src, recursive=True)
    else:
        imgs = [src]
    
    n = len(imgs)
    for i in range(0, n, batch_size):
        j = min(n, i + batch_size)
        batch = [encodeImg(imgs[k]) for k in range(i, j)]
        data = {'images': batch, 'score': score, 'topk': topk}
        data = parse.urlencode(data).encode('utf-8')
        req = request.Request('%s/sclsDet' % url, data=data)
        page = request.urlopen(req).read()
        page = bytes.decode(page)
        page = json.loads(page)
        results = eval(page['data'])
        for l, k in enumerate(range(i, j)):
            print('[%d/%d] %s\n%s' % (j, n, imgs[k], results[l]))

if __name__ == '__main__':
    url = 'http://192.168.11.25:9999'
    src = r'G:\data\scls_data\drink\aiot\test\jl_jsb_lb_500G'
    scls_classify(url, src)


        
